/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-11-16 23:35:22
 * @LastEditors: lhl
 * @LastEditTime: 2024-11-18 11:40:23
 */
/*
 * @Descripttion: 登录界面
 * @version:
 * @Author: lhl
 * @Date: 2024-11-16 23:35:22
 * @LastEditors: lhl
 * @LastEditTime: 2024-11-18 00:18:09
 */
import React from 'react';
import { App, Input, Button, Form } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import styles from './Login.module.less';
import { LoginForm, LoginResponse } from '@/types/login';
import { storage } from '@/utils/storage';
import { useNavigate, useLocation } from 'react-router-dom';
import API from '@/api';

const Login: React.FC = () => {
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();

  const handleSubmit = async (values: LoginForm) => {
    try {
      // 这里添加登录逻辑
      console.log('登录信息:', values);
      const res = await API.user.login(values);
      console.log(res, 'fsf');

      // 存储 token 和用户信息
      storage.set('token', res.token);
      message.success('登录成功');
      // 跳转到首页或指定页面
      // 添加判断逻辑 获取重定向地址，如果没有则默认到首页
      const redirect = location.state?.from?.pathname;
      if (redirect && redirect !== '/login' && redirect !== '/404') {
        navigate(redirect);
      } else {
        navigate('/dashboard'); // 默认跳转到 dashboard
      }
    } catch (error) {
      message.error('登录失败');
    }
  };

  return (
    <div className={styles['login-container']}>
      <div className={styles['login-box']}>
        <h2>Lss React Admin</h2>
        <Form form={form} onFinish={handleSubmit} autoComplete="off">
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
